package com.gao.jedis;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * @Projectname redis_JedisDemo
 * @Filename PhoneCode
 * @Author an
 * @Data 2022/8/18 17:56
 * @Description TODO
 */
public class PhoneCode {
    public static void main(String[] args) {
        //模拟验证码发送
        toRedis("1234567890");
//        getRedisCode("1234567890","754065");

    }

    //验证码校验功能
    public static  void getRedisCode(String phone,String code){
        //从redis中获取验证码
        Jedis jedis = new Jedis("192.168.195.129",6379);

        String codeKey = "VerifyCode"+phone+":code";
        String redisCode = jedis.get(codeKey);
        //做判断
        if (redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }

        jedis.close();

    }



    //每个手机只能发送三次，验证码放到redis中，设置过期时间
    public static void toRedis(String phone){
        //链接redis
        Jedis jedis = new Jedis("192.168.195.129",6379);
        //拼接key
        //手机发送次数key
        String countKey = "Verifycode"+phone+":count";
        //验证码key
        String codeKey = "VerifyCode"+phone+":code";

        //每个手机只能发三次每天
        String count = jedis.get(countKey);
        if (count == null){
            //证明第一次发送
            //设置发送次数为1
            jedis.setex(countKey,24*60*60,"1");
        }else if (Integer.parseInt(count)<=2){
            //发送次数+1
            jedis.incr(countKey);
        }else {
            //大于2,不能发送
            System.out.println("今天的发送次数已经超出3次");
            jedis.close();
            //结束，不再发送验证码
            return;
        }

        //发送的验证码要放到redis
        String vode = getCode();
        jedis.setex(codeKey,120,vode);
        jedis.close();

    }

    //1. 生成6位密码
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i=0;i<6;i++){
            int rand = random.nextInt(10);
            code+=rand;
        }
        return code;
    }


    @Test
    public void times() throws ParseException {
        long now = System.currentTimeMillis();
        SimpleDateFormat sdfOne = new SimpleDateFormat("yyyy-MM-dd");
        long overTime = (now - (sdfOne.parse(sdfOne.format(now)).getTime()))/1000;
        //当前毫秒数
        System.out.println(now);
        //当前时间  距离当天凌晨  秒数 也就是今天过了多少秒
        System.out.println(overTime);
        //当前时间  距离当天晚上23:59:59  秒数 也就是今天还剩多少秒
        long timeNext = 24*60*60 - overTime;
        System.out.println(timeNext);
        //当天凌晨毫秒数
        System.out.println(sdfOne.parse(sdfOne.format(now)).getTime());
        //当天凌晨日期
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.print(sdfTwo.format(sdfOne.parse(sdfOne.format(now)).getTime()));
    }


}
